package fmi.chesstern.ui.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import fmi.chesstern.game.events.GameStateChangedEvent;
import fmi.chesstern.game.events.GameStateChangedListener;
import fmi.chesstern.pieces.ChessPieceColor;

public class ChessBoardFrame extends JFrame {
	private static final long serialVersionUID = 3660599600176046240L;
	
	private JButton undoButton;
	private JLabel currentPlayerLabel;
	private GUIBoardState guiState;
	
	private class stateChangeHandler implements GameStateChangedListener {
		@Override
		public void handleEvent(GameStateChangedEvent event) {
			undoButton.setEnabled(guiState.getGameState().canUndoMove());
			currentPlayerLabel.setText("Current player: "
				+ (guiState.getGameState().getGameBoardState().getCurrentPlayer() == ChessPieceColor.WHITE
				? "WHITE" : "BLACK"));
		}
	}

	public ChessBoardFrame(ChessBoard board, final GUIController controller, GUIBoardState guiState) {
		super("Chesstern");
		
		this.guiState = guiState;
		
		add(board, BorderLayout.CENTER);
		
		JPanel controls = new JPanel();
		controls.setLayout(new FlowLayout());
		
		JButton newGameButton = new JButton("New game");
		newGameButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				controller.startNewGame();
			}
		});
		controls.add(newGameButton);
		
		undoButton = new JButton("Undo");
		undoButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				controller.undo();
			}
		});
		undoButton.setEnabled(guiState.getGameState().canUndoMove());
		controls.add(undoButton);
		
		currentPlayerLabel = new JLabel("Current player: "
				+ (guiState.getGameState().getGameBoardState().getCurrentPlayer() == ChessPieceColor.WHITE
				? "WHITE" : "BLACK"));
		controls.add(currentPlayerLabel);
		
		add(controls, BorderLayout.SOUTH);
		
		guiState.addGameStateChangedListener(new stateChangeHandler());
	}
}
